package keeto.com.vn.bms.ui.activity;

import hirondelle.date4j.DateTime;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import keeto.com.vn.bms.config.BMSCore;
import keeto.com.vn.bms.config.IBMSConfig;
import keeto.com.vn.bms.infiniteviewpager.InfiniteViewPager;
import keeto.com.vn.bms.model.BMSUserModel;
import keeto.com.vn.bms.model.BasePopupModel;
import keeto.com.vn.bms.model.Hospital;
import keeto.com.vn.bms.model.ListSurgeryModel;
import keeto.com.vn.bms.model.ObjectHeaderExpanModel;
import keeto.com.vn.bms.model.Schedule;
import keeto.com.vn.bms.network.IBMSProtocol;
import keeto.com.vn.bms.ui.adapter.BasePopupAdapter;
import keeto.com.vn.bms.ui.adapter.CalWeekendAdapter;
import keeto.com.vn.bms.ui.adapter.CalendarAdapter;
import keeto.com.vn.bms.ui.adapter.CalendarPagerAdapter;
import keeto.com.vn.bms.ui.adapter.ListExpanSurgeryAdapter;
import keeto.com.vn.bms.ui.adapter.ListSurgeryAdapter;
import keeto.com.vn.bms.ui.adapter.MonthPagerAdapter;
import keeto.com.vn.bms.ui.fragment.CalendarFragment;
import keeto.com.vn.bms.ui.widget.IPopupWindow;
import keeto.com.vn.bms.ui.widget.LogoutDialog;
import keeto.com.vn.bms.ui.widget.WeekendGridView;
import keeto.com.vn.bms.utils.BMSListener;
import keeto.com.vn.bms.utils.BMSSharedPreferences;
import keeto.com.vn.bms.utils.Utils;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ListSurgeryActivity extends FragmentActivity implements OnClickListener, OnChildClickListener, OnGroupClickListener {
	final static int PAGE_LIMIT = 10;
	private final static String ACTION_CREATE_SURGERY= " Create_Surgery";
	private ImageButton btn_title_back;
	private ImageButton btn_title_login;
	private ImageButton btn_view_list_schedule;
	private ImageButton btn_add_schedule;
	private Button btn_sort_by_list;
	private Button btn_sort_by_group;
	private PullToRefreshListView listViewSurgery;
	private ExpandableListView mExpandableListView;
	private BMSSharedPreferences mPreferences;
	private RelativeLayout llCal;
	private InfiniteViewPager mViewPager;
	private ProgressBar mBar;
	private String mAction = null;

	private static int mSortBy = -1;
	private static int mGroupBy = -1;
	private static int pageNumber = 1;
	private static int page_old_Number = -1;
	private static String ObjID="";
	private ArrayList<ListSurgeryModel> ListSugery = new ArrayList<ListSurgeryModel>();
	private ListSurgeryListener mListener = new ListSurgeryListener();
	private static int pageNumberDoctor = 1;

	/*
	 * Pupop
	 */

	private ListSurgeryAdapter mAdapterListView;
	private ListExpanSurgeryAdapter mListExpanSurgeryAdapter;
	private ArrayList<ObjectHeaderExpanModel> listHeader = new ArrayList<ObjectHeaderExpanModel>();
	private HashMap<String, ArrayList<ListSurgeryModel>> listContent = new HashMap<String, ArrayList<ListSurgeryModel>>();
	private ObjectHeaderExpanModel modelHeader; 
	private ArrayList<ListSurgeryModel> mArrContentEx = new ArrayList<ListSurgeryModel>();
	/*
	 * Popup SortBy
	 */
	private IPopupWindow popupSortby;
	private ArrayList<BasePopupModel> arrSortby;
	private	BasePopupAdapter SortByAdapter;
	private ListView listPopup;
	/*
	 * Popup groupby
	 */
	private IPopupWindow popupGroupby;
	private ArrayList<BasePopupModel> arrGroupby;
	private BasePopupModel modelGroupby;

	/*
	 * Calender
	 */
	private Button btnToday;
	private Button btnCalendar;
	private TextView tvCurrenCal;
	private Calendar  mCalendar;
	private ArrayList<CalendarFragment> mFragments;
	private ArrayList<CalendarAdapter> mArrCalAdapter = new ArrayList<CalendarAdapter>();
	private CalendarPageChangeListener calendarPageChangeListener;
	private OnItemClickListener CalItemClickListener;
	protected ArrayList<DateTime> ArrCurDate;
	protected int month = -1;
	protected int year = -1;
	private MonthPagerAdapter pagerAdapter;
	private	CalendarPagerAdapter ViewPagerAdapter;

	/*
	 * end Calendar
	 */

	private LinearLayout llviewPager;
	private RelativeLayout llgridWeekend;
	private WeekendGridView gridWeekend;
	private TextView tvCurrenTime;
	private PullToRefreshListView pulllvCal;
	private static ArrayList<DateTime> ArrWeekend = new ArrayList<DateTime>();
	private CalWeekendAdapter weekendAdapter;
	private ListSurgeryAdapter mAdapterlvCal;
	private ArrayList<ListSurgeryModel> ListSugeryCal = new ArrayList<ListSurgeryModel>();
	private LayoutInflater mInflater;
	private Button btnToDayWeek;
	private Button btnCalWeek;

	public static void actionLaunch(Context context) {
		Intent i = new Intent(context, ListSurgeryActivity.class);
		context.startActivity(i);
	}
	public static void actionLaunchbyCreateSegery(Context context) {
		Intent i = new Intent(context, ListSurgeryActivity.class);
		i.setAction(ACTION_CREATE_SURGERY);
		context.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Intent it = getIntent();
		mAction = it.getAction();

		setContentView(R.layout.list_surgery_layout);
		mPreferences = new BMSSharedPreferences(this);
		mInflater = LayoutInflater.from(this);
		pageNumber =1;
		mSortBy=-1;
		mGroupBy=-1;
		modelGroupby=null;
		initUIcomponent();
		initDataViewpager();
		initDataWeekend();

	}
	@Override
	protected void onResume() {
		super.onResume();
		initData(ObjID);  
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mSortBy = -1;
		mGroupBy = -1;
		pageNumber=1;
		ObjID = "";
		modelGroupby=null;
	}
	private void initUIcomponent() {
		btn_title_back = (ImageButton) findViewById(R.id.btn_tittle_back);
		btn_title_login = (ImageButton) findViewById(R.id.btn_title_login);
		btn_view_list_schedule = (ImageButton) findViewById(R.id.btn_view_list_schedule);
		btn_view_list_schedule.setVisibility(View.GONE);
		btn_add_schedule = (ImageButton) findViewById(R.id.btn_add_schedule);
		btn_add_schedule.setOnClickListener(this);
		btn_sort_by_list = (Button) findViewById(R.id.btn_sort_by_list);
		btn_sort_by_group = (Button) findViewById(R.id.btn_sort_by_group);
		listViewSurgery = (PullToRefreshListView) findViewById(R.id.listView_list_Surgery);
		listViewSurgery.setMode(Mode.BOTH);
		mExpandableListView = (ExpandableListView) findViewById(R.id.expanlistView_list_Surgery);
		llCal = (RelativeLayout)findViewById(R.id.ll_cal_list_surgery);
		tvCurrenCal = (TextView)findViewById(R.id.tv_current_cal);
		mViewPager = (InfiniteViewPager)findViewById(R.id.infinite_pager_Cal);
		btnToday = (Button)findViewById(R.id.btn_cal_today);
		btnCalendar = (Button)findViewById(R.id.btn_calendar);
		btnToday.setOnClickListener(this);
		btnCalendar.setOnClickListener(this);

		llviewPager = (LinearLayout)findViewById(R.id.ll_viewpagerCal);
		llgridWeekend = (RelativeLayout)findViewById(R.id.ll_gridWeekend);
		gridWeekend = (WeekendGridView)findViewById(R.id.grid_calendar_weekend);
		tvCurrenTime = (TextView)findViewById(R.id.tv_currenttime);
		pulllvCal = (PullToRefreshListView)findViewById(R.id.listView_list_Surgery_byCal);
		llgridWeekend.setVisibility(View.GONE);
		llviewPager.setVisibility(View.VISIBLE);
		View view = mInflater.inflate(R.layout.calendar_button_layout, null);
		pulllvCal.getRefreshableView().addFooterView(view);
		btnToDayWeek = (Button)view.findViewById(R.id.btn_cal_today_week);
		btnCalWeek = (Button)view.findViewById(R.id.btn_calendar_week);
		btnToDayWeek.setOnClickListener(this);
		btnCalWeek.setOnClickListener(this);

		mBar = (ProgressBar)findViewById(R.id.pBar_list_Surgery);
		mBar.setVisibility(View.GONE);
		listViewSurgery.setVisibility(View.VISIBLE);
		mExpandableListView.setVisibility(View.GONE);
		llCal.setVisibility(View.GONE);

		btn_title_login.setImageResource(Utils.getLogobyPermission(mPreferences.getUserPermission(ListSurgeryActivity.this)));
		btn_title_login.setOnClickListener(this);
		btn_title_back.setOnClickListener(this);
		btn_sort_by_list.setOnClickListener(this);
		btn_sort_by_group.setOnClickListener(this);

		/*
		 */
		if(mPreferences.getTypeKeyUser(ListSurgeryActivity.this) == IBMSConfig.KEY_TYPE_TECHNICIAL || mPreferences.getTypeKeyUser(ListSurgeryActivity.this) == IBMSConfig.KEY_TYPE_LEADERSHIP){
			btn_add_schedule.setVisibility(View.GONE);
		}
		/*
		 * init data to listview
		 */
		mAdapterListView = new ListSurgeryAdapter(ListSurgeryActivity.this, ListSugery);
		listViewSurgery.setAdapter(mAdapterListView);
		listViewSurgery.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//				CreateScheduleActivity.actionLaunchSergery(ListSurgeryActivity.this, ListSugery.get(position-1));
				CreateScheduleActivity.actionLaunchbyCreateSegery(ListSurgeryActivity.this, ListSugery.get(position-1));
			}
		});
		listViewSurgery.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub
				ObjID ="";
				initData(ObjID);
			}
		});
		/*
		 * init date to expanblelistview
		 */
		mListExpanSurgeryAdapter = new ListExpanSurgeryAdapter(ListSurgeryActivity.this, listHeader, listContent);
		mExpandableListView.setAdapter(mListExpanSurgeryAdapter);
		mExpandableListView.setOnGroupClickListener(this);
		mExpandableListView.setOnChildClickListener(this);

	}

	private void resetView(int groupby){
		switch (groupby) {
		case -1:
			listViewSurgery.setVisibility(View.VISIBLE);
			mExpandableListView.setVisibility(View.GONE);
			llCal.setVisibility(View.GONE);
			break;
		case 1:
			listViewSurgery.setVisibility(View.GONE);
			mExpandableListView.setVisibility(View.VISIBLE);
			llCal.setVisibility(View.GONE);
			break;
		case 2:
			listViewSurgery.setVisibility(View.GONE);
			mExpandableListView.setVisibility(View.VISIBLE);
			llCal.setVisibility(View.GONE);
			break;
		case 3:
			listViewSurgery.setVisibility(View.GONE);
			mExpandableListView.setVisibility(View.VISIBLE);
			llCal.setVisibility(View.GONE);
			break;
		case 4:
			listViewSurgery.setVisibility(View.GONE);
			mExpandableListView.setVisibility(View.VISIBLE);
			llCal.setVisibility(View.GONE);
			break;
		case 5:
			listViewSurgery.setVisibility(View.GONE);
			mExpandableListView.setVisibility(View.GONE);
			llCal.setVisibility(View.VISIBLE);
			llviewPager.setVisibility(View.VISIBLE);
			llgridWeekend.setVisibility(View.GONE);

			break;

		default:
			break;
		}
	}

	private void initData(String ObjId) {
		if (pageNumber>0){
			mBar.setVisibility(View.VISIBLE);
			BMSCore.getInstance(ListSurgeryActivity.this).taskgetListSurgery(mSortBy, mGroupBy, ObjId, mPreferences.getUserAuthKey(ListSurgeryActivity.this), PAGE_LIMIT, pageNumber, mListener);
		}else{
			new Handler().post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					listViewSurgery.onRefreshComplete();	
					pulllvCal.onRefreshComplete();
					mBar.setVisibility(View.GONE);

				}
			});
		}
	}
	private void showPopupSortby() {

		if (popupSortby == null){
			popupSortby = new IPopupWindow(this, R.layout.popup_sortby_layout,
					null, false, btn_sort_by_list.getMeasuredWidth(),


					LayoutParams.WRAP_CONTENT);
			listPopup = (ListView) popupSortby.getView().findViewById(R.id.listPopup);

		}

		arrSortby = Utils.getDataPopupSortby(ListSurgeryActivity.this, R.array.arr_list_popup_sortby);
		if (modelGroupby != null){
			for (int j =0;j<arrSortby.size();j++){
				if (modelGroupby.getKey() == arrSortby.get(j).getKey()){
					arrSortby.remove(j);
				}
			}
		}
		if (mPreferences.getUserPermission(ListSurgeryActivity.this) == IBMSConfig.KEY_TYPE_DOCTOR){
			for(int i = 0;i<arrSortby.size();i++){
				if (arrSortby.get(i).getKey() == IBMSConfig.KEY_TYPE_POPUP_DOCTOR){
					arrSortby.remove(i);
					i--;
//				}else if(arrSortby.get(i).getName().equals(this.getResources().getString(R.string.str_sort_by_sugery))){
//					arrSortby.remove(i);
//					i--;
				}
			}
		}
		
		SortByAdapter = new BasePopupAdapter(ListSurgeryActivity.this, arrSortby);
		listPopup.setAdapter(SortByAdapter);
		listPopup.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				btn_sort_by_list.setText(arrSortby.get(position).getName());
				mSortBy = arrSortby.get(position).getId();
				popupSortby.dismiss();
				switch (mGroupBy) {
				case -1:
					pageNumber=1;
					ListSugery.clear();
					mAdapterListView.notifyDataSetChanged();
					ObjID ="";
					initData(ObjID);
					resetView(mGroupBy);
					break;
				case 1:
				case 2:
				case 3:
				case 4:
				case 5:
					resetView(mGroupBy);
					pageNumber=1;
					for(String key : listContent.keySet()){
						listContent.get(key).clear();
					}
					mListExpanSurgeryAdapter.notifyDataSetChanged();
					if (modelHeader != null)
						ObjID = modelHeader.getId()+"";
					initData(ObjID);
					break;

				default:
					break;
				}

			}
		});
		popupSortby.setAutoHideOutside();
		popupSortby.showAsDropDown(btn_sort_by_list);

	}

	private void showPopupGroupby() {
		if (popupGroupby == null){
			popupGroupby = new IPopupWindow(this, R.layout.popup_sortby_layout,
					null, false, btn_sort_by_group.getMeasuredWidth(),
					LayoutParams.WRAP_CONTENT);
			ListView listPopupGroupby = (ListView) popupGroupby.getView().findViewById(R.id.listPopup);
			arrGroupby = Utils.getDataPopupGroupby(ListSurgeryActivity.this, R.array.arr_list_popup_groupby);
			if (mPreferences.getUserPermission(ListSurgeryActivity.this) == IBMSConfig.KEY_TYPE_DOCTOR){
				for(int i = 0;i<arrGroupby.size();i++){
					if (arrGroupby.get(i).getKey() == IBMSConfig.KEY_TYPE_POPUP_DOCTOR){
						arrGroupby.remove(i);
						i--;
//					}else if(arrGroupby.get(i).getName().equals(this.getResources().getString(R.string.str_groups_by_sugery))){
//						arrGroupby.remove(i);
//						i--;
					}
				}
			}
			BasePopupAdapter GroupByAdapter = new BasePopupAdapter(ListSurgeryActivity.this, arrGroupby);
			listPopupGroupby.setAdapter(GroupByAdapter);
			listPopupGroupby.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					btn_sort_by_group.setText(arrGroupby.get(position).getName());
					pageNumber = 1;
					popupGroupby.dismiss();
					switch (arrGroupby.get(position).getId()) {
					case 0:
						mGroupBy = -1;
						pageNumber = page_old_Number;
						listHeader.clear();
						listContent.clear();
						modelGroupby = null;
						mListExpanSurgeryAdapter.notifyDataSetChanged();
						resetView(mGroupBy);
						
						break;
					case 1:
						mGroupBy = 1;
						listHeader.clear();
						listContent.clear();
						modelGroupby = arrGroupby.get(position);
						mListExpanSurgeryAdapter.notifyDataSetChanged();
						BMSCore.getInstance(ListSurgeryActivity.this).taskGetHopital(mPreferences.getUserAuthKey(ListSurgeryActivity.this), mListener);
						resetView(mGroupBy);

						break;
					case 2:
						mGroupBy=2;
						modelGroupby = arrGroupby.get(position);

						listHeader.clear();
						listContent.clear();
						mListExpanSurgeryAdapter.notifyDataSetChanged();
						BMSCore.getInstance(ListSurgeryActivity.this).taskGetTypeUser(mPreferences.getUserAuthKey(ListSurgeryActivity.this), 3,PAGE_LIMIT,pageNumberDoctor, mListener);
						resetView(mGroupBy);

						break;
					case 3:
						modelGroupby = arrGroupby.get(position);

						listHeader.clear();
						listContent.clear();
						mListExpanSurgeryAdapter.notifyDataSetChanged();
						mGroupBy=3;
						BMSCore.getInstance(ListSurgeryActivity.this).taskGetSchedule(mPreferences.getUserAuthKey(ListSurgeryActivity.this), mListener);
						resetView(mGroupBy);

						break;
					case 4:
						modelGroupby = arrGroupby.get(position);
						mGroupBy=4;
						listHeader.clear();
						loadheaderMedicalRecord();
						resetView(mGroupBy);

						break;
					case 5:
						modelGroupby = null;
						listHeader.clear();
						listContent.clear();
						mListExpanSurgeryAdapter.notifyDataSetChanged();
						mGroupBy=5;
						resetView(mGroupBy);
						break;

					default:
						break;
					}

				}

			});
			popupGroupby.setAutoHideOutside();
			popupGroupby.showAsDropDown(btn_sort_by_group);
		}else{
			popupGroupby.showAsDropDown(btn_sort_by_group); 

		}
	}

	private void loadheaderMedicalRecord(){
		new Handler().post(new Runnable() {

			@Override
			public void run() {
				listHeader.clear();
				listContent.clear();
				String [] list = ListSurgeryActivity.this.getResources().getStringArray(R.array.arr_list_level);
				for (int i = 0; i < list.length; i++) {
					listHeader.add(new ObjectHeaderExpanModel(i+1,list[i].toString(),""));
				}
				for(ObjectHeaderExpanModel model : listHeader){
					listContent.put(model.getName(), new ArrayList<ListSurgeryModel>());
				}
				mListExpanSurgeryAdapter.notifyDataSetChanged();
				for (int k = 0;k<listHeader.size();k++){
					Log.e( "SIze EX", "HEADER "  + listHeader.get(k).getName() );
				}
				for(String key : listContent.keySet()){
					Log.e( "SIze EX", key + " SIZE Content" + listContent.get(key).size());

				}
				Log.e( "SIze EX", "HEADER  Size"  + mListExpanSurgeryAdapter.getGroupCount()  + listHeader.size());

			}
		});

	}



	//////////////////////////////////////////////////////////////Start Calendar//////////////////////////////////////////////////////////////////////
	private void initDataViewpager() {
		mCalendar = Calendar.getInstance();
		month = mCalendar.get(Calendar.MONTH)+1;
		year = mCalendar.get(Calendar.YEAR);

		DateTime currentDateTime = new DateTime(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH)+1, 1, 0, 0, 0, 0);
		calendarPageChangeListener = new CalendarPageChangeListener();
		calendarPageChangeListener.setCurrentPage(InfiniteViewPager.OFFSET);
		calendarPageChangeListener.setCurrentDateTime(currentDateTime);

		CalendarAdapter adapter1 = getNewCalendarAdapter(currentDateTime.getMonth(), currentDateTime.getYear());
		ArrCurDate = adapter1.getArrDate();

		DateTime nextDateTime = currentDateTime.plus(0, 1, 0, 0, 0, 0, 0,DateTime.DayOverflow.LastDay);
		CalendarAdapter adapter2 = getNewCalendarAdapter(nextDateTime.getMonth(), nextDateTime.getYear());

		DateTime next2DateTime = nextDateTime.plus(0, 1, 0, 0, 0, 0, 0,DateTime.DayOverflow.LastDay);
		CalendarAdapter adapter3 = getNewCalendarAdapter(next2DateTime.getMonth(), next2DateTime.getYear());

		DateTime prevDateTime = currentDateTime.minus(0, 1, 0, 0, 0, 0, 0,DateTime.DayOverflow.LastDay);
		CalendarAdapter adapter4 = getNewCalendarAdapter(prevDateTime.getMonth(), prevDateTime.getYear());

		mArrCalAdapter.add(adapter1);
		mArrCalAdapter.add(adapter2);
		mArrCalAdapter.add(adapter3);
		mArrCalAdapter.add(adapter4);


		pagerAdapter = new MonthPagerAdapter(getSupportFragmentManager());
		mFragments = pagerAdapter.getArrayList();
		for(int i=0 ; i<MonthPagerAdapter.NUMBER_OF_PAGES;i++){
			CalendarFragment fragment = mFragments.get(i);
			CalendarAdapter iAdapter = mArrCalAdapter.get(i);
			fragment.setAdapter(iAdapter);
			fragment.setOnItemClickListener(getCalendarItemClickListener());
		}
		ViewPagerAdapter = new CalendarPagerAdapter(pagerAdapter);
		mViewPager.setAdapter(ViewPagerAdapter);

		calendarPageChangeListener.setCalendarAdapters(mArrCalAdapter);
		mViewPager.setOnPageChangeListener(calendarPageChangeListener);

		refreshCalendarView();
		pagerAdapter.notifyDataSetChanged();
		ViewPagerAdapter.notifyDataSetChanged();
		Log.e("CUR", "CUR INit" + mViewPager.getCurrentItem());


	}

	public CalendarAdapter getNewCalendarAdapter(int month, int year){
		return new CalendarAdapter(month, year, this);

	}
	public void setCalendarDateTime(DateTime dateTime) {
		month = dateTime.getMonth();
		year = dateTime.getYear();
		refreshCalendarView();
	}
	public void refreshCalendarView() {

		tvCurrenCal.setText(this.getResources().getString(R.string.str_month) + (month) + " - " + this.getResources().getString(R.string.str_year) + year );
		for(CalendarAdapter adapter : mArrCalAdapter){
			adapter.updateToday();
			adapter.notifyDataSetChanged();
		}
	}
	private OnItemClickListener getCalendarItemClickListener(){
		if (CalItemClickListener == null){
			CalItemClickListener = new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					DateTime dateTime = ArrCurDate.get(position);
					if (dateTime != null){
						ArrWeekend.clear();
						ArrWeekend = Utils.getFullWeekend(dateTime, 2);
						int mindex  = -1;
						for (int i=0; i <ArrWeekend.size();i++){
							if (ArrWeekend.get(i).getDay() == dateTime.getDay()){
								mindex = i;
								break;
							}
						}
						weekendAdapter = new CalWeekendAdapter(ListSurgeryActivity.this, ArrWeekend,mindex);
						gridWeekend.setAdapter(weekendAdapter);
						weekendAdapter.notifyDataSetChanged();

						llgridWeekend.setVisibility(View.VISIBLE);
						llviewPager.setVisibility(View.GONE);


						pageNumber = 1;
						ObjID = Utils.convertDateTimetoString(dateTime);
						initData(ObjID);

						tvCurrenTime.setText(Utils.convertDatetoStringFull(dateTime, ListSurgeryActivity.this));
					}
				}
			};
		}

		return CalItemClickListener;

	}

	private void resetCalendar(){
		new Handler().post(new Runnable() {

			@Override
			public void run() {
				mViewPager.getCurrentItem();

				float Numberpage = mViewPager.getCurrentItem() - 1000;
				if (Numberpage != 0 ){
					for (int i=0; i< Math.abs(Numberpage); i++){
						if (Numberpage >0){
							mViewPager.setCurrentItem(calendarPageChangeListener.getCurrentPage() - 1);
						}else{
							mViewPager.setCurrentItem(calendarPageChangeListener.getCurrentPage() + 1);
						}

					}
				}

			}
		});
	}

	/*
	 * Init Grid Weekened
	 * 
	 */
	private void initDataWeekend(){
		weekendAdapter = new CalWeekendAdapter(ListSurgeryActivity.this, ArrWeekend,-1);
		gridWeekend.setAdapter(weekendAdapter);
		weekendAdapter.notifyDataSetChanged();
		mAdapterlvCal = new  ListSurgeryAdapter(ListSurgeryActivity.this, ListSugeryCal);
		pulllvCal.setAdapter(mAdapterlvCal);

		pulllvCal.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub
				initData(ObjID);
			}
		});

		gridWeekend.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				weekendAdapter.setIndex(position);
				weekendAdapter.notifyDataSetChanged();
				ListSugeryCal.clear();
				mAdapterlvCal.notifyDataSetChanged();
				ObjID = Utils.convertDateTimetoString(ArrWeekend.get(position));
				pageNumber = 1;
				initData(ObjID);
			}
		});
	}

	//////////////////////////////////////////////////////////////End Calendar//////////////////////////////////////////////////////////////////////
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_tittle_back:
			this.finish();

			break;
		case R.id.btn_title_login:
			if (mPreferences.getUserAuthKey(ListSurgeryActivity.this).equals("")){
				LoginBMSActivity.actionLaunch(ListSurgeryActivity.this);
			}else{
				LogoutDialog dialog = new LogoutDialog(ListSurgeryActivity.this );
				dialog.show();
			}
			break;
		case R.id.btn_sort_by_list:
			showPopupSortby();
			break;
		case R.id.btn_sort_by_group:
			showPopupGroupby();
			break;
		case R.id.btn_cal_today:
			resetCalendar();
			break;
		case R.id.btn_calendar:
			llCal.setVisibility(View.VISIBLE);
			llviewPager.setVisibility(View.VISIBLE);
			llgridWeekend.setVisibility(View.GONE);
			break;
		case R.id.btn_cal_today_week:
			resetCalendar();
			llCal.setVisibility(View.VISIBLE);
			llviewPager.setVisibility(View.VISIBLE);
			llgridWeekend.setVisibility(View.GONE);
			break;
		case R.id.btn_calendar_week:
			llCal.setVisibility(View.VISIBLE);
			llviewPager.setVisibility(View.VISIBLE);
			llgridWeekend.setVisibility(View.GONE);

			break;
		case R.id.btn_add_schedule:
			switch (mPreferences.getTypeKeyUser(ListSurgeryActivity.this)) {
			case 1:
				CreateScheduleActivity.actionLaunch(ListSurgeryActivity.this);
				break;
			case 2: 
				break;
			case 3:
				CreateScheduleActivity.actionLaunch(ListSurgeryActivity.this);
				break;
			case 4:
				CreateScheduleActivity.actionLaunch(ListSurgeryActivity.this);
				break;
			case 5: 
				break;

			default:
				break;
			}
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub

		if (mAction!= null && mAction.equals(ACTION_CREATE_SURGERY)){
			this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	class ListSurgeryListener extends BMSListener{
		@Override
		public void finishGetListSugery(final int returnCode, final int countpage,
				final ArrayList<ListSurgeryModel> lists) {
			// TODO Auto-generated method stub
			super.finishGetListSugery(returnCode, countpage, lists);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (returnCode == IBMSProtocol.STATUS_CODE_OK && lists != null){
						if (pageNumber< countpage){
							pageNumber +=1;
						}else{
							pageNumber = -1;
						}
						page_old_Number = pageNumber;
						if (mGroupBy >0 && mGroupBy <5){
							mArrContentEx.clear();
							mArrContentEx.addAll(lists);
							for(String key : listContent.keySet()){
								if (modelHeader.getName().equals(key)){
									listContent.get(key).addAll(mArrContentEx);
								}

							}

							mListExpanSurgeryAdapter.notifyDataSetChanged();

						}else if (mGroupBy == 5){
							ListSugeryCal.addAll(lists);
							mAdapterlvCal.notifyDataSetChanged();
							pulllvCal.onRefreshComplete();
						}else{
							ListSugery.addAll(lists);
							mAdapterListView.notifyDataSetChanged();
							listViewSurgery.onRefreshComplete();
						}

					}else if(returnCode == IBMSProtocol.STATUS_CODE_GENERIC_FAIL_CONECTTION){
						Toast.makeText(ListSurgeryActivity.this, ListSurgeryActivity.this.getResources().getString(R.string.error_network_connection), Toast.LENGTH_SHORT).show();
					}
					listViewSurgery.onRefreshComplete();	
					pulllvCal.onRefreshComplete();
					mBar.setVisibility(View.GONE);
				}
			});
		}
		@Override
		public void finishGetHopital(final int returnCode, String resultMsg,
				final ArrayList<Hospital> listHopital) {
			// TODO Auto-generated method stub
			super.finishGetHopital(returnCode, resultMsg, listHopital);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (returnCode == IBMSProtocol.STATUS_CODE_OK){
						listHeader.clear();
						listContent.clear();
						for(int i =0; i<listHopital.size();i++){
							listHeader.add(new ObjectHeaderExpanModel(Integer.parseInt(listHopital.get(i).getId()), listHopital.get(i).getName(),listHopital.get(i).getDesc()));
						}
						for(ObjectHeaderExpanModel model : listHeader){
							listContent.put(model.getName(), new ArrayList<ListSurgeryModel>());
						}
						for (int k = 0;k<listHeader.size();k++){
						}
						mListExpanSurgeryAdapter.notifyDataSetChanged();
					}
					mBar.setVisibility(View.GONE);
				}
			});
		}

		@Override
		public void finishGetTypeUsers(final int returnCode, String resultMsg,
				int recordNumber, int countPage, int groupID,
				final ArrayList<BMSUserModel> listUserModel) {
			// TODO Auto-generated method stub
			super.finishGetTypeUsers(returnCode, resultMsg, recordNumber, countPage,
					groupID, listUserModel);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (returnCode == IBMSProtocol.STATUS_CODE_OK){
						listHeader.clear();
						listContent.clear();
						for(int i =0; i<listUserModel.size();i++){
							listHeader.add(new ObjectHeaderExpanModel(Integer.parseInt(listUserModel.get(i).getUserID()), listUserModel.get(i).getFullName(),listUserModel.get(i).getGroupName()));
						}
						for(ObjectHeaderExpanModel model : listHeader){
							listContent.put(model.getName(), new ArrayList<ListSurgeryModel>());
						}

						mListExpanSurgeryAdapter.notifyDataSetChanged();

					}
					mBar.setVisibility(View.GONE);
				}
			});
		}
		@Override
		public void finishGetSchedule(final int returnCode, String resultMsg,
				final ArrayList<Schedule> listSchedule) {
			// TODO Auto-generated method stub
			super.finishGetSchedule(returnCode, resultMsg, listSchedule);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (returnCode == IBMSProtocol.STATUS_CODE_OK){
						listHeader.clear();
						listContent.clear();
						for(int i =0; i<listSchedule.size();i++){
							listHeader.add(new ObjectHeaderExpanModel(listSchedule.get(i).getId(), listSchedule.get(i).getName(),listSchedule.get(i).getDesc()));
						}
						for(ObjectHeaderExpanModel model : listHeader){
							listContent.put(model.getName(), new ArrayList<ListSurgeryModel>());
						}

						mListExpanSurgeryAdapter.notifyDataSetChanged();
					}else if(returnCode==IBMSProtocol.STATUS_CODE_EXIT_RECORD){
						Toast.makeText(ListSurgeryActivity.this, ListSurgeryActivity.this.getResources().getString(R.string.error_data_server), Toast.LENGTH_SHORT).show();
					}else if(returnCode==IBMSProtocol.STATUS_CODE_GENERIC_FAIL_CONECTTION){
						Toast.makeText(ListSurgeryActivity.this, ListSurgeryActivity.this.getResources().getString(R.string.error_network_connection), Toast.LENGTH_SHORT).show();
					}
					else if(returnCode==IBMSProtocol.STATUS_CODE_GENERIC_FAIL) {
						Toast.makeText(ListSurgeryActivity.this, ListSurgeryActivity.this.getResources().getString(R.string.error_perpose), Toast.LENGTH_SHORT).show();
					}

					mBar.setVisibility(View.GONE);
				}
			});
		}
	}

	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {
		// TODO Auto-generated method stub

		if (mListExpanSurgeryAdapter.getChildrenCount(groupPosition) == 0){
			modelHeader  =	(ObjectHeaderExpanModel) mListExpanSurgeryAdapter.getGroup(groupPosition);
			pageNumber =1;
			ObjID = modelHeader.getId()+"";
			initData(ObjID);
		}

		return false;
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		// TODO Auto-generated method stub
		CreateScheduleActivity.actionLaunchSergery(ListSurgeryActivity.this, (ListSurgeryModel) mListExpanSurgeryAdapter.getChild(groupPosition, childPosition));

		return false;
	}

	/*
	 * OnpagechangeListener
	 */

	public class CalendarPageChangeListener implements OnPageChangeListener{
		private int currentPage = InfiniteViewPager.OFFSET;
		private DateTime currentDateTime;
		private ArrayList<CalendarAdapter> calendarAdapters;

		public int getCurrentPage() {
			Log.e("CUR", "get Currenpage" + mViewPager.getCurrentItem() + " Currenpage" +  currentPage + " pos ");

			return currentPage;

		}
		public void setCurrentPage(int curPage) {
			this.currentPage = curPage;

		}
		public DateTime getCurrentDateTime() {
			return currentDateTime;
		}

		public void setCurrentDateTime(DateTime dateTime) {
			this.currentDateTime = dateTime;
			setCalendarDateTime(currentDateTime);
		}

		public ArrayList<CalendarAdapter> getCalendarAdapters() {
			return calendarAdapters;
		}
		public void setCalendarAdapters(ArrayList<CalendarAdapter> calendarAdapters) {
			this.calendarAdapters = calendarAdapters;
		}

		private int getNext(int position) {
			return (position + 1) % MonthPagerAdapter.NUMBER_OF_PAGES;
		}
		private int getPrevious(int position) {
			return (position + 3) % MonthPagerAdapter.NUMBER_OF_PAGES;
		}
		public int getCurrent(int position) {
			return position % MonthPagerAdapter.NUMBER_OF_PAGES;
		}

		public void resetCalendarAdapter(int position){
			CalendarAdapter curAdapter = calendarAdapters.get(getCurrent(position));
			CalendarAdapter previewAdapter = calendarAdapters.get(getPrevious(position));
			CalendarAdapter nextAdapter = calendarAdapters.get(getNext(position));

			if (position == currentPage){
				curAdapter.setAdapterCalendar(currentDateTime);
				curAdapter.notifyDataSetChanged();

				previewAdapter.setAdapterCalendar(currentDateTime.minus(0, 1, 0,
						0, 0, 0, 0, DateTime.DayOverflow.LastDay));
				previewAdapter.notifyDataSetChanged();

				nextAdapter.setAdapterCalendar(currentDateTime.plus(0, 1, 0, 0,
						0, 0, 0, DateTime.DayOverflow.LastDay));
				nextAdapter.notifyDataSetChanged();

			}else if (position > currentPage){
				currentDateTime = currentDateTime.plus(0, 1, 0, 0, 0, 0, 0,
						DateTime.DayOverflow.LastDay);
				nextAdapter.setAdapterCalendar(currentDateTime.plus(0, 1, 0, 0,
						0, 0, 0, DateTime.DayOverflow.LastDay));
				nextAdapter.notifyDataSetChanged();
			}else if (position<currentPage){
				currentDateTime = currentDateTime.minus(0, 1, 0, 0, 0, 0, 0,
						DateTime.DayOverflow.LastDay);
				previewAdapter.setAdapterCalendar(currentDateTime.minus(0, 1, 0,
						0, 0, 0, 0, DateTime.DayOverflow.LastDay));
				previewAdapter.notifyDataSetChanged();
			}
			currentPage = position;
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageSelected(int position) {
			// TODO Auto-generated method stub

			resetCalendarAdapter(position);
			setCalendarDateTime(currentDateTime);

			CalendarAdapter icaldapter = calendarAdapters.get(position % MonthPagerAdapter.NUMBER_OF_PAGES );
			ArrCurDate.clear();
			ArrCurDate.addAll(icaldapter.getArrDate());
			refreshCalendarView();

		}

	}
}
